package com.lcxw.hxzbapi.service;

import com.alibaba.fastjson.JSONObject;
import com.lcxw.hxzbapi.controller.membercontroller.MemberRealization;
import com.lcxw.hxzbapi.dao.mapper.YwpdMemberMapper;
import com.lcxw.hxzbapi.entity.pojo.YwpdMember;
import com.lcxw.hxzbapi.entity.response.Response;
import com.lcxw.hxzbapi.feign.thirdService.OutRegistService;
import com.lcxw.hxzbapi.tencentim.common.TencentImRealization;
import com.lcxw.hxzbcommon.common.StringUtil;
import com.lcxw.hxzbcommon.entity.ErrorCode;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

@Component
@Service
public class YwpdMemberService {

    private Logger logger = LoggerFactory.getLogger(YwpdMemberService.class);

    @Resource
    YwpdMemberMapper ywpdMemberMapper;

    @Resource
    MemberRealization memberRealization;

    @Resource
    TencentImRealization tencentImRealization;

    @Resource
    OutRegistService outRegistService;

    /**
     * 注册方法
     *
     * @param ywpdMember 用户注册页面带过来的值
     * @return 注册响应
     */
    public Response register(String parentUserId, YwpdMember ywpdMember) {
        Response response = new Response();
        Map<String, Object> data = new LinkedHashMap<>();

        //生成UserId
        long userId = StringUtil.generateShortUuid();
        ywpdMember.setUserId(userId);

        //生成注册时间 yyyy-MM-dd HH:mm:ss
        ywpdMember.setRegTime(StringUtil.getDateTime());

        String telephone = ywpdMember.getTelephone();
        String format = String.format("%04d", new Random().nextInt(9999));
        //生成userName，生成规则为 “MEM”+手机号

        String userName = "20".concat(telephone.substring(7)).concat(format);
        ywpdMember.setUserName(userName);
        ywpdMember.setSign(0);

        try {
            String token = memberRealization.genToken(userId);
            ywpdMemberMapper.addYwpdMember(ywpdMember);
            response.setCode(0);
            response.setDesc("success");
            data.put("userId", userId);
            data.put("token", token);
            response.setData(data);
        } catch (DuplicateKeyException e) {
            logger.error("插入的数据已存在： " + e.getCause());
            response.setCode(ErrorCode.NO_PERMISSION);
            response.setDesc("用户注册失败，数据已存在。");
            return response;
        } catch (Exception e) {
            e.printStackTrace();
            logger
                .error("注册失败，数据库操作失败，注册数据为 {}", ywpdMember.toString());
            response.setCode(ErrorCode.DB_OPERATE_FAIL);
            response.setDesc("用户注册失败，数据库操作异常。");
            return response;
        }

        //调用注册关系管理接口
        if (StringUtil.isEmpty(parentUserId)) {
            parentUserId = "";
        }
        JSONObject requestBody = new JSONObject();
        requestBody.put("userId", userId + "");
        requestBody.put("parentUserId", parentUserId);
        requestBody.put("phone", telephone);

        //想腾讯IM导入用户
        tencentImRealization.importImUser(userId);

    /*    //维护用户关系
        outRegistService.OutRegist(requestBody);*/

        return response;
    }

    public YwpdMember selectYwpdMemberById(long id) throws Exception {

        return ywpdMemberMapper.selectYwpdMemberById(id);
    }

    public YwpdMember selectYwpdMemberByUserId(long userId) {
        return ywpdMemberMapper.selectYwpdMemberByUserId(userId);
    }
    public YwpdMember selectMemberUserIdOrTel(String userIdOrTel) {
        return ywpdMemberMapper.selectMemberUserIdOrTel(userIdOrTel);
    }

    public YwpdMember selectYwpdMemberByUserName(String userName) throws Exception {
        return ywpdMemberMapper.selectYwpdMemberByUserName(userName);
    }

    public YwpdMember selectYwpdMemberByTelephone(String telephone) throws Exception {
        return ywpdMemberMapper.selectYwpdMemberByTelephone(telephone);
    }

    /**
     * 提供一个方便查询用户的方法
     *
     * @param o 传入参数可以是id userId userName telephone；；
     * @return YwpdMember
     * @throws Exception dbexception
     */
    public YwpdMember selectYwpdMember(Object o) throws Exception {
        YwpdMember ywpdMember;

        if (o instanceof Long) {
            long idOrUserId = (long) o;
            ywpdMember = selectYwpdMemberById(idOrUserId);

            if (null == ywpdMember) {
                ywpdMember = selectYwpdMemberByUserId(idOrUserId);
            }
            return ywpdMember;

        } else if (o instanceof String) {
            String nameOrTelephone = (String) o;
            ywpdMember = selectYwpdMemberByTelephone(nameOrTelephone);

            if (null == ywpdMember) {
                ywpdMember = selectYwpdMemberByUserName(nameOrTelephone);

            }

            return ywpdMember;
        } else {
            return null;
        }

    }

    /**
     * @param ywpdMember 修改后的对象
     * @throws Exception dbexception
     */
    public int updateYwpdMember(YwpdMember ywpdMember) throws Exception {
        return ywpdMemberMapper.updateYwpdMember(ywpdMember);
    }

    //用户充值方法,通过userId充值
    public int updateCoinByUserId(int coin, long userId) {
        return ywpdMemberMapper.updateCoinByUserId(coin, userId);
    }

    //用户充值方法,通过userId充值
    public int updateCoinByUserName(int coin, String userName) throws Exception {
        return ywpdMemberMapper.updateCoinByUserName(coin, userName);
    }


    //查询头像
    public String selectImgUrlByuserId(long userId) {
        return ywpdMemberMapper.selectImgUrlByUserId(userId);
    }

    //查询昵称
    public String selectNickNameByUserId(long userId) {
        return ywpdMemberMapper.selectNickNameByUserId(userId);
    }

    public Map<String, String> selectNickAndImgUrl(long userId) {
        return ywpdMemberMapper.selectNickAndImgUrl(userId);
    }

    public List<YwpdMember> selectMemberDynamic(String fromRegTime, String toRegTime, Integer sign,
        Integer liveStatus, Integer cancelled, int pageIndex, int pageSize) throws Exception {
        return ywpdMemberMapper
            .selectMemberDynamic(fromRegTime, toRegTime, sign, liveStatus, cancelled, pageIndex,
                pageSize);
    }

    public int selectCountOfMemberDynamic(String fromRegTime, String toRegTime, Integer sign,
        Integer liveStatus,
        Integer cancelled) {
        return ywpdMemberMapper
            .selectCountOfMemberDynamic(fromRegTime, toRegTime, sign, liveStatus, cancelled);
    }

    public YwpdMember selectByOpenId(String openId) {
        return ywpdMemberMapper.selectByopenId(openId);
    }

    public YwpdMember selectByiosId(String iosId) {
        return ywpdMemberMapper.selectByiosId(iosId);
    }

    public Map selectLngAndLat(long userId) {
        return ywpdMemberMapper.selectLngAndLat(userId);
    }

    public List<YwpdMember> selectAll() {
        return ywpdMemberMapper.selectAll();
    }

    public List<YwpdMember> selectAliveMember() {
        return ywpdMemberMapper.selectAliveMember();
    }

    public List<YwpdMember> selectVip() {
        return ywpdMemberMapper.selectVip();
    }


    public Long selectUserId(long dynamicId){
        return ywpdMemberMapper.selectUserId(dynamicId);
    }
}
